package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.pojo.BlackList;
import com.tanhua.common.pojo.Settings;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PageResult;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.dubbo.pojo.UserLike;
import com.tanhua.dubbo.pojo.Visitors;
import com.tanhua.dubbo.vo.*;
import com.tanhua.server.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestHeader;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Don
 */
@Service
@Slf4j
public class MyCenterService {
    @Autowired
    private UserInfoService userInfoService;

    @Reference
    private UserLikeApi userLikeApi;

    @Reference
    private VisitorsApi visitorsApi;

    @Autowired
    private RecommentUserService recommentUserService;

    @Autowired
    private IMService imService;

    @Autowired
    private TanHuaService tanHuaService;

    @Autowired
    private SettingsService settingsService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BlackService blackService;


    /**
     * 查询个人信息
     *
     * @param userId
     * @return
     */
    public UserInfoVo queryUserInfoByUserId(Long userId) {
        // 判断是否传入用户id
        if (ObjectUtil.isEmpty(userId)) {
            //如果查询id为null，就表示查询当前用户信息
            userId = UserThreadLocal.get().getId();
        }
        // 查询用户信息
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(userId);
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().toString().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }

    /**
     * 修改用户资料
     *
     * @param userInfoVo
     */
    public Boolean updateUserInfoByUser(UserInfoVo userInfoVo) {
        // 获取当前的用户
        User user = UserThreadLocal.get();

        UserInfo userInfo = new UserInfo();
        // 封装数据
        userInfo.setUserId(user.getId());
        userInfo.setNickName(userInfoVo.getNickname());
        userInfo.setBirthday(userInfoVo.getBirthday());
        userInfo.setSex(StringUtils.equalsAnyIgnoreCase(userInfoVo.getGender(), "1") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setIncome(StringUtils.replaceAll(userInfoVo.getIncome(), "k", ""));
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setMarriage(userInfo.getMarriage() == "1" ? "已婚" : "未婚");

        return this.userInfoService.updateUserInfoByUserId(userInfo);
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     *
     * @return
     */
    public CountsVo queryCounts() {
        CountsVo countsVo = new CountsVo();

        User user = UserThreadLocal.get();
        // 相互喜欢数
        Long eachLoveCount = this.userLikeApi.queryMutualLoveCount(user.getId());
        countsVo.setEachLoveCount(Convert.toInt(eachLoveCount));

        // 喜欢数
        Long loveCount = this.userLikeApi.queryLoveCount(user.getId());
        countsVo.setLoveCount(Convert.toInt(loveCount));

        // 粉丝数
        Long fanCount = this.userLikeApi.queryFanCount(user.getId());
        countsVo.setFanCount(Convert.toInt(fanCount));

        return countsVo;
    }

    /**
     *  互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     *
     *  @param type
     * @param page
     * @param pageSize
     * @param nickName
     */
    public PageResult queryLikeList(Integer type, Integer page, Integer pageSize, String nickName) {
        // 封装page和pageSize
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        // 获取userId
        User user = UserThreadLocal.get();
        Long userId = user.getId();

        List<Object> userIdList = new ArrayList<>();

        //1 互相关注    queryMutualLikeList
        //2 我关注      queryLoveList
        //3 粉丝       queryFanList
        //4 谁看过我    topVisitor
        switch (type){
            //1 互相关注
            case 1:{
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryMutualLikeList(page, pageSize, userId);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId");
                break;
            }
            //2 我关注
            case 2:{
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryLoveList(page, pageSize, userId);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(),"likeUserId");
                break;
            }
            //3 粉丝
            case 3:{
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryFanList(page, pageSize, userId);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(),"userId");
                break;
            }
            // 谁看过我
            case 4:{
                PageInfo<Visitors> pageInfo = this.visitorsApi.topVisitor(page, pageSize, userId);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(),"visitorUserId");
                break;
            }
            default:
                return pageResult;
        }

        // 判断userIdList是否为空
        if(CollUtil.isEmpty(userIdList)){
            return pageResult;
        }

        // 查询符合条件的userInfo集合
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",userIdList);
        if(StrUtil.isNotEmpty(nickName)){
            queryWrapper.like("nick_name",nickName);
        }

        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        List<UserLikeListVo> userLikeListVos = new ArrayList<>();
        // 遍历userInfoList
        for (UserInfo userInfo : userInfoList) {
            UserLikeListVo userLikeListVo = new UserLikeListVo();
            // 封装数据
            userLikeListVo.setAge(userInfo.getAge());
            userLikeListVo.setAvatar(userInfo.getLogo());
            userLikeListVo.setCity(userInfo.getCity());
            userLikeListVo.setEducation(userInfo.getEdu());
            userLikeListVo.setGender(userInfo.getSex().name().toLowerCase());
            userLikeListVo.setId(userInfo.getUserId());
            userLikeListVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "未婚") ? 0 : 1);
            userLikeListVo.setNickname(userInfo.getNickName());

            //是否喜欢
            userLikeListVo.setAlreadyLove(this.userLikeApi.isLike(userId,userInfo.getUserId()));

            // 获取缘分值
            Double score = this.recommentUserService.queryScore(userId, userInfo.getUserId());
            userLikeListVo.setMatchRate(Convert.toInt(score));

            userLikeListVos.add(userLikeListVo);
        }

        pageResult.setItems(userLikeListVos);

        return pageResult;
    }

    /**
     * 取消喜欢
     *
     * @param userId
     */
    public Boolean disLike(Long userId) {
        // 获取当前用户
        User user = UserThreadLocal.get();
        // 判断当前用户与此用户是否喜欢
        Boolean flag = this.userLikeApi.isMutualLike(user.getId(),userId);
        // 取消喜欢
        this.userLikeApi.notLikeUser(user.getId(), userId);


        if(flag){
            // 删除环信上的好友关系
            try {
                this.imService.removeUser(userId);
            } catch (Exception e) {
                log.error("救救救救。。。就这，就这啊",e);
            }
        }
        return flag;
    }

    /**
     *  粉丝 - 喜欢
     *
     * @param userId
     */
    public Boolean LoveFan(Long userId) {
        // 成为粉丝
        return  this.tanHuaService.likeUser(userId);
    }


    /**
     * 用户通用设置 - 读取
     *
     * @return
     */
    public SettingsVo queryNotification() {
        User user = UserThreadLocal.get();
        SettingsVo settingsVo = new SettingsVo();

        // 封装用户id以及手机号
        settingsVo.setId(user.getId());
        settingsVo.setPhone(user.getMobile());

        // 封装 陌生人问题 ：strangerQuestion
        String question = this.tanHuaService.queryQuestion(user.getId());
        settingsVo.setStrangerQuestion(question);

        // 调用方法 查询推送喜欢、评论以及公告通知
        Settings settings = this.settingsService.querySettings(user.getId());
        if(ObjectUtil.isNotEmpty(settings)){
            // 封装 推送喜欢、评论以及公告通知
            settingsVo.setLikeNotification(settings.getLikeNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
        }

        return settingsVo;
    }

    /**
     *  设置陌生人问题 - 保存
     *
     * @param content
     * @return
     */
    public void saveQuestions(String content) {
        User user = UserThreadLocal.get();

        // 在questionService调用保存方法
        this.questionService.saveQuestion(user.getId(),content);
    }


    /**
     *  通知设置 - 保存
     *
     * @param likeNotification
     * @param pinglunNotification
     * @param gonggaoNotification
     */
    public void updateNotification(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        User user = UserThreadLocal.get();
        this.settingsService.updateNotification(user.getId(),likeNotification,pinglunNotification,gonggaoNotification);
    }



    /**
     * 查询黑名单
     *
     * @param page
     * @param pageSize
     */
    public PageResult queryBlackList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        // 查询黑名单
        IPage<BlackList> blackList = this.blackService.queryBlackList(user.getId(), page, pageSize);

        // 封装pageResult
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setPages(Convert.toInt(blackList.getPages()));
        pageResult.setCounts(Convert.toInt(blackList.getTotal()));

        List<BlackList> records = blackList.getRecords();
        // 判断records是否为空
        if(ObjectUtil.isEmpty(records)){
            return pageResult;
        }

        // 获取黑名单用户的id集合
        List<Object> userIds = CollUtil.getFieldValues(records, "blackUserId");
        // 获取黑名单用户的集合
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);
        List<BlackListVo> blackListVos = new ArrayList<>();

        // 遍历userInfoList
        for (UserInfo userInfo : userInfoList) {
            // 封装响应前端的数据
            BlackListVo blackListVo = new BlackListVo();
            blackListVo.setAge(userInfo.getAge());
            blackListVo.setAvatar(userInfo.getLogo());
            blackListVo.setGender(userInfo.getSex().name().toLowerCase());
            blackListVo.setId(userInfo.getUserId());
            blackListVo.setNickname(userInfo.getNickName());

            blackListVos.add(blackListVo);
        }

        pageResult.setItems(blackListVos);

        return pageResult;
    }

    /**
     * 黑名单 - 移除
     *
     * @param userId
     */
    public void deleteBlack(Long userId) {
        User user = UserThreadLocal.get();
        // 调用黑名单删除方法
        this.blackService.deleteBlack(user.getId(), userId);
    }

    public Boolean isAlreadyLove(Long likeUserId) {
        User user = UserThreadLocal.get();
        return this.userLikeApi.isLike(user.getId(),likeUserId);
    }
}
